package cn.itlaobing.web.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itlaobing.entity.Accounts;
import cn.itlaobing.service.AccountService;

@Controller
@RequestMapping("/students")
public class AccountController {
	@Autowired
	private AccountService accountService;
	
	//公共的方法
	@ModelAttribute
	public void prepareDate(@PathVariable(required=false) Integer id,Model model) {
		if(id==null) {
			model.addAttribute("account",new Accounts());
		}else {
			
			model.addAttribute("account", accountService.findById(id));
		}
	}
	
	/*@RequestMapping()
	public String index(Model model) {
		Accounts account=accountService.findById(1);
		model.addAttribute("account",account);
		return "/index";
	}*/
	@GetMapping
	public  String show (Model model) {
		List<Accounts> accounts=accountService.findAll();
		model.addAttribute("account", accounts);
		return "/show";
	}
	@GetMapping("/add")
	public String add() {
		return "/add";
	}
	@PostMapping("/add")
	public String add(@ModelAttribute("account") @Valid Accounts accounts,
			BindingResult bindingResualt,Model model
			) {
		if(bindingResualt.hasErrors()) {
			model.addAttribute("account", accounts);
			return "/add";
		}
		accountService.save(accounts);
		return "redirect:/students";
	}
	//修改
	@GetMapping("/{id}/update")
	public String update() {
		return "/update";
	}
	@PostMapping("/{id}/update")
		public String update(@ModelAttribute("account") @Valid Accounts accounts,
				BindingResult bindingResualt) {
			accountService.updateById(accounts);
			return  "redirect:/students";
	}
	
	//删除
	@GetMapping("/{id}/del")
	@ResponseBody
	public String del(@PathVariable Integer id) {
		accountService.del(id);
		return  "ok";
	}
	
}
	
	
	
	
	

